#!/usr/bin/env python

from ftplib import *;
import StringIO, sys, getopt,os,urllib, traceback,re,cgi;
import cgitb

FETCHURL = "http://netsupport.tsinghua.edu.cn/mfdzb/freeip.htm"
maxnum = 5
def err_usage():
    print 'usage: %s [-m num_of_news]'%sys.argv[0]
    sys.exit(1)

if __name__ == "__main__":
    cgitb.enable()
#    cgi.test()
#    print "Content-type: text/plain; charset=gb2312\n";
    print "Content-type: application/plain; charset=gb2312\n";
    print 'Content-disposition: inline; filename="getfreeip.bat"'

    yourgateway = os.environ['REMOTE_ADDR']
    yourgateway = yourgateway[:yourgateway.rfind('.')]+".1"
    
    opts, args = getopt.getopt(sys.argv[1:], 'm:')
    for optpair in opts:  # like this[('-d', ''), ('-k', '3')...]
        if optpair[0]=='-m':
            try:
                maxnum = int(optpair[1])
            except:
                err_usage()
            if maxnum ==-1:
                print "can't be -1!"
                sys.exit(1)

    orifile = urllib.urlopen(FETCHURL)
    import time
    filename = "".join(["freeip"]+["%02d"%x for x in time.localtime()[:3]]+[".bat"])

    try:    
        for line in orifile.readlines():
            line=line.strip()
            mat=re.search('^([.0-9]+) +([.0-9]+) +([.0-9]+)',line)
            if mat:
                print "route add %s mask %s %s metric 10"%(mat.group(1),
                                                           mat.group(3),
                                                           yourgateway)
    except KeyboardInterrupt:
        outfile.close()
        orifile.close()
